#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = 'api.dwh@google.com (Dan Holevoet)'


import cgi
import logging
import os
import simplejson
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import *
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import migrator


class MainPage(webapp.RequestHandler):
  def get(self):
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
    self.response.out.write(template.render(path, template_values))


class TOSException(Exception):
  def __init__(self, value):
    self.value = value

  def __str__(self):
    return repr(self.value)


class Migrate(webapp.RequestHandler):
  def post(self):
    url = self.request.get('url')
    raw = self.request.get('raw')
    wrappers = self.request.get('wrappers') == 'on'
    tos = self.request.get('tos') == 'on'

    migrations = db.GqlQuery('SELECT * FROM Migration')

    warning = ''

    try:
      if tos:
        if url:
          result = urlfetch.fetch(url)
          if result.status_code == 200:
            m = migrator.Migrator(result.content, migrations, wrappers)
        elif raw:
          m = migrator.Migrator(raw, migrations, wrappers)
        else:
          raise migrator.InputMissingError()

        m.migrate()
      else:
        raise TOSException('You must accept the Terms of Service.')
    except InvalidURLError:
      template_values = {
          'warning': 'An invalid URL was entered.'
      }
    except migrator.InputMissingError, e:
      template_values = {
          'warning': e.message
      }
    except TOSException, e:
      template_values = {
          'warning': 'You must accept the Terms of Service.'
      }
    else:
      template_values = {
          'raw': simplejson.JSONEncoder().encode(
              m.raw_code.replace('<', '&lt;').replace('>', '&gt;')),
          'migrated': simplejson.JSONEncoder().encode(
              m.string.replace('<', '&lt;').replace('>', '&gt;')),
          'migrated_text': cgi.escape(m.string),
          'annotations': m.annotations
      }

    path = os.path.join(os.path.dirname(__file__), 'templates/migrate.html')
    self.response.out.write(template.render(path, template_values))


class Admin(webapp.RequestHandler):
  def get(self):
    template_values = {
        'migrations': db.GqlQuery('SELECT * FROM Migration')
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):
    migration = migrator.Migration()
    migration.old = self.request.get('old')
    migration.new = self.request.get('new')
    migration.regex = self.request.get('regex') == 'on'
    migration.wrapper = self.request.get('wrapper')
    migration.annotation = self.request.get('annotation')

    migration.put()
    self.redirect('/admin')

application = webapp.WSGIApplication(
    [('/', MainPage),
     ('/migrate', Migrate),
     ('/admin', Admin)],
     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
